import cv2
import numpy as np

# 读取图片
img = cv2.imread("demo_edge.jpg", cv2.IMREAD_GRAYSCALE)

# 确定阈值
threshold_value = 15

# 创建一个空白的图像
binary_img = np.zeros_like(img)

# 对每个像素进行遍历，并根据阈值二值化
# binary_img[img > threshold_value] = 255
for i in range(img.shape[0]):
    for j in range(img.shape[1]):
        if img[i,j] > threshold_value:
            binary_img[i,j] = 255
        else:
            binary_img[i,j] = 0

# 将结果分配给变量
thresh = binary_img
ret = None


# 统计置255的像素数量
white_pixels = 0
rows, cols = binary_img.shape
for i in range(rows):
    for j in range(cols):
        if binary_img[i, j] == 255:
            white_pixels += 1

# 统计总像素数量
total_pixels = rows * cols

# 计算白色像素所占的比例
white_ratio = white_pixels / total_pixels


# 保存图像
cv2.imwrite('demo_edge_thresh1.jpg',thresh)
print('White Ratio:', round(white_ratio, 2))